package controller;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Lid;
import org.hibernate.Query;
import org.hibernate.Session;
import persistence.SessionManager;

/**
 *
 * @author Sujen / Niels
 */

public class LoginController extends HttpServlet {

@Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {    

        // Hier volgt de 5 bovenknoppen active array, in gebruik in include/top_nav.jsp
        Boolean[] topNavActive = new Boolean[]{
            false, false, false, true, false};
        request.setAttribute("topNavActive", topNavActive);

        String address = "login.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }  
    
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession sessie = request.getSession();
        Session session;
        session = SessionManager.openSession();

        response.setContentType("text/html");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Lid l;
        try {
            Query q = session.createQuery("from Lid as lid where lid.lidLogin = '" + username + "' AND lid.lidPassword = '" + password + "'");
            l = (Lid) q.uniqueResult();
            if (null != l && l.isLidActivated() && !l.isLidDeleted()) {
                sessie.setAttribute("currentUser", l);
                response.sendRedirect("MijnDryves");
            } else {
                if (null == l) {
                    request.setAttribute("tempUsername", username);
                    request.setAttribute("error", "Usernaam of Password niet correct!");
                } else {
                    if (!l.isLidActivated()) {
                        request.setAttribute("error", "Account niet geactiveerd!");
                    }
                    if (l.isLidDeleted()) {
                        request.setAttribute("error", "Account geblokkeerd!");
                    }
                }
                String address = "/login.jsp";
                RequestDispatcher dispatcher = request.getRequestDispatcher(address);
                dispatcher.forward(request, response);
            }
        } finally {
            session.close();
        }
    }
}
